package com.xnyzc.lhy.didi.service.impl.work;

import com.xnyzc.lhy.common.component.didi.DiDiUrlConstant;
import com.xnyzc.lhy.common.entity.DiDiRv;
import com.xnyzc.lhy.common.exception.DiDiException;
import com.xnyzc.lhy.common.penum.EDiDiErrorCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.RequestMethodUtil;
import com.xnyzc.lhy.common.util.retry.RetryUtil;
import com.xnyzc.lhy.common.util.sign.AttestationTool;
import com.xnyzc.lhy.didi.entity.param.work.BindVirtualNumberParam;
import com.xnyzc.lhy.didi.entity.param.work.BindWorkParam;
import com.xnyzc.lhy.didi.entity.param.work.CreateWorkParam;
import com.xnyzc.lhy.didi.entity.param.work.UnbundleVirtualNumberParam;
import com.xnyzc.lhy.didi.entity.param.work.UnbundleWorkParam;
import com.xnyzc.lhy.didi.entity.param.work.UpdateWorkParam;
import com.xnyzc.lhy.didi.entity.param.work.WorkUrgentParam;
import com.xnyzc.lhy.didi.entity.results.didi.work.BindNumberResults;
import com.xnyzc.lhy.didi.entity.results.didi.work.CreateWorkResults;
import com.xnyzc.lhy.didi.entity.work.OaSysWorksheetCall;
import com.xnyzc.lhy.didi.mapper.work.OaSysWorksheetCallMapper;
import com.xnyzc.lhy.didi.mapper.work.OaSysWorksheetMapper;
import com.xnyzc.lhy.didi.service.work.WorkService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 工单相关
 * </p>
 *
 * @author wangshuo
 * @since 2019-10-07
 */
@Slf4j
@Service
public class WorkServiceImpl implements WorkService {

    @Autowired
    private OaSysWorksheetCallMapper oaSysWorksheetCallMapper;

    @Autowired
    private OaSysWorksheetMapper oaSysWorksheetMapper;

    /**
     * 新建工单
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getCreateWork(CreateWorkParam param){
        CreateWorkResults results=new CreateWorkResults();
        if(StringUtils.isBlank(param.getWorksheet_id())) {
            return DiDiRv.wrap(EDiDiErrorCode.parameterError,results);
        }
        log.info("请求滴滴接口调用成功");
        String url= DiDiUrlConstant.didiUrl+DiDiUrlConstant.ARK_WORK_API+"?act=create";
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        param.setApp_id(DiDiUrlConstant.didiAppId);
        String signParameter =AttestationTool.getSign(param, DiDiUrlConstant.JSON_PARAM);
        Map<String, Object> map = transStringToMap(signParameter, "&", "=");
        JSONObject json = JSONObject.fromObject(map);
        String data=RequestMethodUtil.requestMethodJson(json,url);
        log.error("调用滴滴新建工单接口返回结果{}", data);
        com.alibaba.fastjson.JSONObject jsonObject=com.alibaba.fastjson.JSONObject.parseObject(data);
        if(jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())){
            // 成功
            com.alibaba.fastjson.JSONObject dataObject =jsonObject.getJSONObject("data");
            results.setWorksheet_id(dataObject.getString("worksheet_id"));
            return DiDiRv.wrap(EDiDiErrorCode.success,results);
        }
        try {
            return com.alibaba.fastjson.JSONObject.parseObject(data, DiDiRv.class);
        } catch (Exception e) {
            throw DiDiException.create(EDiDiErrorCode.jsonConvertError);
        }
    }

    /**
     * 更新工单
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getUpdateWork(UpdateWorkParam param){
        if(StringUtils.isBlank(param.getWorksheet_id())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        if (CheckUtil.strIsEmpty(param.getContent())) {
            param.setContent("审核通过");
        }
        log.info("请求滴滴接口调用成功");
        String url=DiDiUrlConstant.didiUrl+DiDiUrlConstant.ARK_WORK_API+"?act=update";
        Date date = new Date();
        param.setApp_id(DiDiUrlConstant.didiAppId);
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        String signParameter =AttestationTool.getSign(param, DiDiUrlConstant.JSON_PARAM);
        Map<String, Object> map = transStringToMap(signParameter, "&", "=");
        JSONObject json = JSONObject.fromObject(map);
        String data = null;
        try {
            data= RetryUtil.requestMethodJson(json, url, 5, 1000L, 1.3);
        } catch (Exception e) {
            log.error("调用滴滴免单接口失败");
            throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
        }
        if (CheckUtil.strIsEmpty(data)) {
            throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
        }
        log.error("调用滴滴更新工单接口返回结果{}", data);
        com.alibaba.fastjson.JSONObject jsonObject=com.alibaba.fastjson.JSONObject.parseObject(data);
        if(jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())){
            // 成功
            return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
        }
        try {
            return com.alibaba.fastjson.JSONObject.parseObject(data, DiDiRv.class);
        } catch (Exception e) {
            throw DiDiException.create(EDiDiErrorCode.jsonConvertError);
        }
    }

    /**
     * 解绑虚拟号接口
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getUnbundleNumber(UnbundleVirtualNumberParam param){
        if(CheckUtil.objIsEmpty(param.getCall_id())){
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        OaSysWorksheetCall worksheetCall=oaSysWorksheetCallMapper.selectById(param.getCall_id());
        if(CheckUtil.objIsEmpty(worksheetCall)){
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        if(CheckUtil.objIsNotEmpty(worksheetCall.getBindId())){
            UnbundleWorkParam parameter=new UnbundleWorkParam();
            String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.UNBIND_PHONE_API;
            parameter.setApp_id(DiDiUrlConstant.didiAppId);
            Date date = new Date();
            String timestamp = String.valueOf(date.getTime() / 1000);
            parameter.setTimestamp(timestamp);
            parameter.setBind_id(worksheetCall.getBindId());
            String signParameter = AttestationTool.getSign(parameter, DiDiUrlConstant.JSON_PARAM);
            Map<String, Object> map = transStringToMap(signParameter, "&", "=");
            JSONObject json = JSONObject.fromObject(map);
            String data=RequestMethodUtil.requestMethodJson(json,url);
            com.alibaba.fastjson.JSONObject jsonObject=com.alibaba.fastjson.JSONObject.parseObject(data);
            if(jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())){
                return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
            }
            else {
                return DiDiRv.wrapError(EDiDiErrorCode.unbindPhoneFailed);
            }
        }
        else{
            return DiDiRv.wrapError(EDiDiErrorCode.unbindPhoneFailed);
        }
    }

    /**
     * 绑定虚拟号接口
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getBindNumber(BindVirtualNumberParam param) {
        BindWorkParam parameter = new BindWorkParam();
        if (CheckUtil.objIsEmpty(param.getCusPhone()) || StringUtils.isEmpty(param.getTicket_no())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }

        BindNumberResults results = new BindNumberResults();

        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.BIND_PHONE_API;
        parameter.setId(param.getTicket_no());
        parameter.setPhone(param.getCusPhone());
        parameter.setApp_id(DiDiUrlConstant.didiAppId);
        parameter.setType(3);// 固定传 3订单中乘客手机号
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        parameter.setTimestamp(timestamp);
        String signParameter = AttestationTool.getSign(parameter, DiDiUrlConstant.JSON_PARAM);
        Map<String, Object> map = transStringToMap(signParameter, "&", "=");
        JSONObject json = JSONObject.fromObject(map);
        String data = RequestMethodUtil.requestMethodJson(json, url);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(data);

        if (jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {
            com.alibaba.fastjson.JSONObject dataObject = jsonObject.getJSONObject("data");
            Long id = IDUtil.nextId();
            results.setPhone_number(dataObject.getString("v_phone"));
            results.setBind_id(dataObject.getString("bind_id"));
        }
        else
        {
            DiDiRv.wrapErrorCode(EDiDiErrorCode.bingPhoneFailed);
        }

        return DiDiRv.wrap(EDiDiErrorCode.success, results);
    }

    /**
     * 工单加急接口
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getWorkUrgent(WorkUrgentParam param){
        BindNumberResults results=new BindNumberResults();
        if(StringUtils.isBlank(param.getWorksheet_id())||StringUtils.isBlank(param.getContent())) {
            return DiDiRv.wrap(EDiDiErrorCode.parameterError,results);
        }
        String url=DiDiUrlConstant.didiUrl+DiDiUrlConstant.ARK_WORK_API+"?act=updateLevel&case_id=1&sandbox_token=2LHFHwkKSZ8ZfGJOGC1w74iJwa%2BnMLJkN4c%2BR4LnD79cwWGYUJaEK1l3jdPBZjjT";
        param.setTimestamp(String.valueOf(System.currentTimeMillis()));
        String signParameter =AttestationTool.getSign(param, DiDiUrlConstant.JSON_PARAM);
        Map<String, Object> map = transStringToMap(signParameter, "&", "=");
        JSONObject json = JSONObject.fromObject(map);
        String data=RequestMethodUtil.requestMethodJson(json,url);
        com.alibaba.fastjson.JSONObject jsonObject=com.alibaba.fastjson.JSONObject.parseObject(data);
        if(jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())){
            // 成功
        }
        return DiDiRv.wrap(EDiDiErrorCode.success,results);
    }

    public static Map<String, Object> transStringToMap(String mapString, String separator, String pairSeparator) {
        Map<String, Object> map = new HashMap<String, Object>();
        String[] fSplit = mapString.split(separator);
        for (int i = 0; i < fSplit.length; i++) {
            if (fSplit[i]==null||fSplit[i].length()==0) {
                continue;
            }
            String[] sSplit = fSplit[i].split(pairSeparator);
            String value = fSplit[i].substring(fSplit[i].indexOf('=') + 1, fSplit[i].length());
            map.put(sSplit[0], value);
        }
        return map;
    }
}
